package com.smartsoft.demo.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.smartsoft.demo.R;
import com.smartsoft.demo.domain.Contact;

/**
 * Contact edit fragment lets user to edit contact information.
 * Has transparent background.
 */
public class ContactEditFragment extends Fragment {

    //Contact key for saving it in bundle
    public static final String CONTACT = "contact";
    // code to recognize camera result
    private static final int IMAGE_REQUEST_CODE = 1503;

    //contact avatar uri
    private String avatarUri;

    //controls to display contact fields
    private ImageView avatar;
    private EditText firstName;
    private EditText lastName;
    private EditText phone;
    private EditText email;
    private EditText skype;
    private Button preview;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        //get view from fragment layout
        View view = inflater.inflate(R.layout.contact_edit, container, false);
        //init controls for editing contact fields
        avatar      = (ImageView)(view.findViewById(R.id.imageView));
        firstName   = (EditText) (view.findViewById(R.id.firstName));
        lastName    = (EditText) (view.findViewById(R.id.lastName));
        phone       = (EditText) (view.findViewById(R.id.phone));
        email       = (EditText) (view.findViewById(R.id.email));
        skype       = (EditText) (view.findViewById(R.id.skype));
        preview     = (Button)   (view.findViewById(R.id.goPreview));

        //start choose avatar on avatar click
        avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseImage(view);
            }
        });
        //go to preview
        preview.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                goPreview();
            }
        });
        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //save contact data
        outState.putSerializable(CONTACT, getContact());
    }

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //restore contact data
        if (savedInstanceState != null) {
            Contact contact = (Contact)savedInstanceState.get(CONTACT);
            if (contact != null) {
                fillFields(contact);
            }
        }
    }

    /**
     * Fill controls with data from contact
     * @param contact - domain entity
     */
    private void fillFields(Contact contact) {
        if (contact.getAvatarUri() != null) {
            avatar.setImageURI(Uri.parse(contact.getAvatarUri()));
        }
        firstName.setText(contact.getFirstName());
        lastName.setText(contact.getLastName());
        email.setText(contact.getEmail());
        phone.setText(contact.getPhone());
        skype.setText(contact.getSkype());
    }

    /**
     * Collect data from controls in entity
     * @return
     */
    private Contact getContact() {
        Contact contact = new Contact();
        contact.setAvatarUri(avatarUri);
        contact.setEmail(email.getText().toString());
        contact.setFirstName(firstName.getText().toString());
        contact.setLastName(lastName.getText().toString());
        contact.setSkype(skype.getText().toString());
        contact.setPhone(phone.getText().toString());
        return contact;
    }

    /**
     * Replace contact edit fragment with contact preview fragment
     */
    public void goPreview() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        Fragment previewFragment = new ContactPreviewFragment();
        //put data to contact preview fragment
        Bundle args = new Bundle();
        args.putSerializable(CONTACT, getContact());
        previewFragment.setArguments(args);

        //replace contact edit fragment with contact preview fragment
        ft.replace(R.id.fragmentPlace, previewFragment);
        //to enable back button support
        ft.addToBackStack(null);
        ft.commit();
    }

    /**
     * Open android choose picture dialog. Result will come in startActivityForResult
     * @param view
     */
    public void chooseImage(View view) {
        Intent cameraIntent = new Intent(Intent.ACTION_GET_CONTENT);
        cameraIntent.setType("image/*");
        cameraIntent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(cameraIntent, IMAGE_REQUEST_CODE);
    }

    /**
     * Result from calling CATEGORY_OPENABLE Activity
     * @param requestCode code of request that we put as parametr on startActivityForResult
     * @param resultCode result saying is request success or not
     * @param data that comes as result
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IMAGE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            //save image uri and set it to image view
            avatarUri = data.getData().toString();
            avatar.setImageURI(data.getData());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}